package com.freesky.provider.search.service.impl;

import com.freesky.common.exception.EMallException;
import com.freesky.common.utils.reponse.JSONResponse;
import com.freesky.common.utils.reponse.JSONResponseDiretor;
import com.freesky.common.vo.SolrInfo;
import com.freesky.provider.search.mapper.ItemSearchMapper;
import com.freesky.provider.search.service.ISearchItemService;
import com.freesky.provider.search.vo.SearchItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author: 陈玉林
 * @date: 2018/11/29 15:24
 * @description:
 */
@Service
@Slf4j
public class SearchItemServiceImpl implements ISearchItemService {


    @Autowired
    private ItemSearchMapper itemSearchMapper;

    @Autowired
    private SolrClient solrClient;

    @Value("${solr.url}")
    private String solrUrl;

    @Value("${solr.core}")
    private String solrCore;


    @Override
    public JSONResponse importAllItems() throws Exception{

        //查询商品列表
        List<SearchItem> itemList = itemSearchMapper.getItemList();

        //遍历商品列表
        for (SearchItem searchItem : itemList) {
            String image = searchItem.getPicUrl();
            if (image != null && !"".equals(image)) {
                String[] strings = image.split(",");
                image = strings[0];
            } else {
                image = "";
            }
            searchItem.setPicUrl(image);
            // 创建Document对象
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id", searchItem.getItemId());
            document.addField("itemId", searchItem.getItemId());
            document.addField("salePrice", String.valueOf(searchItem.getSalePrice()));
            document.addField("itemName", searchItem.getItemName());
            document.addField("subTitle", searchItem.getSubTitle());
            document.addField("picUrl", searchItem.getPicUrl());
            document.addField("categoryName", searchItem.getCategoryName());
            document.addField("cid", searchItem.getCid());
            solrClient.add(solrCore, document);
            solrClient.commit(solrCore);
        }

        log.info("更新Solr索引成功");

        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @Override
    public JSONResponse getInfo() {
        SolrInfo info = new SolrInfo();
        info.setConnect(true);
        info.setCoreName(solrCore);
        info.setNodeNum(1L);
        info.setUrl(solrUrl);
        return JSONResponseDiretor.buildSuccessJSONResponse(info);
    }
}
